<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <title>thread的使用 - 欢迎来到SY的博客</title><meta name="description" content="thread的使用"><meta property="og:title" content="thread的使用" />
<meta property="og:description" content="thread的使用" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://acking-you.gitee.io/posts/thread%C3%A7%C3%A4%C3%A7/" /><meta property="og:image" content="https://acking-you.gitee.io/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2022-08-21T00:00:00+00:00" />
<meta property="article:modified_time" content="2022-08-21T00:00:00+00:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://acking-you.gitee.io/logo.png"/>

<meta name="twitter:title" content="thread的使用"/>
<meta name="twitter:description" content="thread的使用"/>
<meta name="application-name" content="FeelIt">
<meta name="apple-mobile-web-app-title" content="FeelIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="canonical" href="https://acking-you.gitee.io/posts/thread%C3%A7%C3%A4%C3%A7/" /><link rel="prev" href="https://acking-you.gitee.io/posts/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread/" /><link rel="next" href="https://acking-you.gitee.io/posts/%C3%A5%C3%A7%C2%BA%C3%A7%C3%A5%C3%A6api%C3%A8%C3%A8/" /><link rel="stylesheet" href="/css/page.min.css"><link rel="stylesheet" href="/css/home.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "thread的使用",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/acking-you.gitee.io\/posts\/thread%C3%A7%C3%A4%C3%A7\/"
        },"genre": "posts","keywords": "thread的使用","wordcount":  3036 ,
        "url": "https:\/\/acking-you.gitee.io\/posts\/thread%C3%A7%C3%A4%C3%A7\/","datePublished": "2022-08-21T00:00:00+00:00","dateModified": "2022-08-21T00:00:00+00:00","publisher": {
            "@type": "Organization",
            "name": "作者"},"author": {
                "@type": "Person",
                "name": "作者"
            },"description": "thread的使用"
    }
    </script></head><body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="欢迎来到SY的博客">欢迎来到SY的博客</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="#" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="欢迎来到SY的博客">欢迎来到SY的博客</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="#" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="#" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><div class="menu-item"><a href="javascript:void(0);" class="theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div></div>
    </div>
</header><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single" data-toc="disable"><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://w.wallhaven.cc/full/9m/wallhaven-9m2pww.jpg"
        data-srcset="https://w.wallhaven.cc/full/9m/wallhaven-9m2pww.jpg, https://w.wallhaven.cc/full/9m/wallhaven-9m2pww.jpg 1.5x, https://w.wallhaven.cc/full/9m/wallhaven-9m2pww.jpg 2x"
        data-sizes="auto"
        alt="https://w.wallhaven.cc/full/9m/wallhaven-9m2pww.jpg"
        title="thread的使用" /></div><div class="single-card" data-image="true"><h2 class="single-title animated flipInX">thread的使用</h2><div class="post-meta">
                <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>作者</a></span>&nbsp;<span class="post-category">出版于  <a href="/categories/cpp%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%BC%82%E6%AD%A5%E4%B8%8E%E5%B9%B6%E5%8F%91/"><i class="far fa-folder fa-fw"></i>CPP多线程异步与并发</a></span></div>
                <div class="post-meta-line"><span><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2022-08-21">2022-08-21</time></span>&nbsp;<span><i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 3036 字</span>&nbsp;
                    <span><i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 7 分钟</span>&nbsp;</div>
            </div>
            
            <hr><div class="details toc" id="toc-static"  data-kept="">
                    <div class="details-summary toc-title">
                        <span>目录</span>
                        <span><i class="details-icon fas fa-angle-right"></i></span>
                    </div>
                    <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#浅谈进程和线程">浅谈进程和线程</a></li>
    <li><a href="#1stdthread">1、std::thread</a></li>
    <li><a href="#2join">2、join()</a></li>
    <li><a href="#3detach">3、detach()</a></li>
    <li><a href="#4解决detach的问题">4、解决detach()的问题</a></li>
  </ul>
</nav></div>
                </div><div class="content" id="content"><h2 id="浅谈进程和线程">浅谈进程和线程</h2>
<ul>
<li>
<p><strong>进程：一个应用程序被操作系统拉起来加载到内存之后开始执行结束的这样一个过程。简单来说，进程就是一个可执行程序(*.exe)。比如打开一个桌面应用软件就是开启一个进程，每个进程是独立的，独占一层地址空间。</strong></p>
</li>
<li>
<p><strong>线程：是一个进程的实体，是被系统独立分配和调度的基本单位。也就是说，线程是CPU可执行调度的最小单位。进程本身并不能获取CPU的时间，只有线程可以。</strong></p>
</li>
<li>
<p><strong>从属关系：进程&gt;线程，一个进程可以拥有多个线程。</strong></p>
</li>
<li>
<p><strong>每个线程可以共享同样的内存空间，开销比较小。</strong></p>
</li>
<li>
<p><strong>每个进程拥有独立内存空间，因此开销更大。</strong></p>
</li>
<li>
<p><strong>对于高性能并行计算，更好的是多线程。</strong></p>
</li>
</ul>
<h2 id="1stdthread">1、std::thread</h2>
<p>C++11 中提供的线程类叫做 <strong>std::thread</strong>，基于这个类创建一个新的线程非常的简单，只需要提供线程函数或者函数对象即可，并且可以同时指定线程函数的参数。</p>
<p>下面是std::thread线程类的构造函数：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="c1">// ①
</span><span class="c1"></span><span class="kr">thread</span><span class="p">()</span> <span class="k">noexcept</span><span class="p">;</span>
<span class="c1">// ②
</span><span class="c1"></span><span class="kr">thread</span><span class="p">(</span> <span class="kr">thread</span><span class="o">&amp;&amp;</span> <span class="n">other</span> <span class="p">)</span> <span class="k">noexcept</span><span class="p">;</span>
<span class="c1">// ③
</span><span class="c1"></span><span class="k">template</span><span class="o">&lt;</span> <span class="k">class</span> <span class="nc">Function</span><span class="p">,</span> <span class="k">class</span><span class="err">... </span><span class="nc">Args</span> <span class="o">&gt;</span>
<span class="k">explicit</span> <span class="kr">thread</span><span class="p">(</span> <span class="n">Function</span><span class="o">&amp;&amp;</span> <span class="n">f</span><span class="p">,</span> <span class="n">Args</span><span class="o">&amp;&amp;</span><span class="p">...</span> <span class="n">args</span> <span class="p">);</span>
<span class="c1">// ④
</span><span class="c1"></span><span class="kr">thread</span><span class="p">(</span> <span class="k">const</span> <span class="kr">thread</span><span class="o">&amp;</span> <span class="p">)</span> <span class="o">=</span> <span class="k">delete</span><span class="p">;</span>
</code></pre></div><ul>
<li>
<p>构造函数①：默认构造函，构造一个线程对象，在这个线程中不执行任何处理动作</p>
</li>
<li>
<p>构造函数②：移动构造函数，将 other 的线程所有权转移给新的 thread 对象。之后 other 不再表示执行线程。</p>
</li>
<li>
<p>构造函数③：创建线程对象，并在该线程中执行函数 f 中的业务逻辑，args 是要传递给函数 f 的参数</p>
<p>任务函数 f 的可选类型有很多，具体如下：</p>
<ul>
<li>普通函数，类成员函数，匿名函数，仿函数（这些都是可调用对象类型）</li>
<li>可以是可调用对象包装器类型，也可以是使用绑定器绑定之后得到的类型（仿函数）</li>
</ul>
</li>
<li>
<p>构造函数④：使用 =delete 显示删除拷贝构造，不允许线程对象之间的拷贝</p>
</li>
</ul>
<p>下面通过std::thread简单模拟下载文件和用户交互的过程，代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;string&gt;</span><span class="cp">
</span><span class="cp"></span><span class="cm">/*模拟下载任务-多线程的异步处理*/</span>
<span class="kt">void</span> <span class="nf">downLoad</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">file</span><span class="p">)</span>
<span class="p">{</span>
	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;DownLoading&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">file</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;(&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">i</span> <span class="o">*</span> <span class="mi">10</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;%)&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
		<span class="n">std</span><span class="o">::</span><span class="n">this_thread</span><span class="o">::</span><span class="n">sleep_for</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">milliseconds</span><span class="p">(</span><span class="mi">500</span><span class="p">));</span>
	<span class="p">}</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;DownLoading completed:&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">file</span><span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">void</span> <span class="nf">interact</span><span class="p">()</span>
<span class="p">{</span>
	<span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">name</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cin</span> <span class="o">&gt;&gt;</span> <span class="n">name</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;Hello&#34;</span> <span class="o">&lt;&lt;</span> <span class="s">&#34; &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">name</span><span class="o">&lt;&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t</span><span class="p">([</span><span class="o">&amp;</span><span class="p">](){</span>
        <span class="n">downLoad</span><span class="p">(</span><span class="s">&#34;hello.zip&#34;</span><span class="p">);</span>
    <span class="p">});</span>
    <span class="n">interact</span><span class="p">();</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><p>但是这样写代码会出现一个错误，我们在main()中创建了一个子线程t，在子线程中执行下载任务(downLoad函数)，然后主线程执行用户交互(interact函数)，但是在执行完interact交互函数之后，主线程就执行结束了，并且会退出当前进程，但是子线程的下载任务还未结束，所以程序会崩溃。</p>
<p>要想让主线程等待子线程那么我们可以通过join()实现，下面讲解一下join()。</p>
<h2 id="2join">2、join()</h2>
<p>**join() 字面意思是连接一个线程，意味着主动地等待线程的终止（线程阻塞）。**在某个线程中通过子线程对象调用 join() 函数，调用这个函数的线程被阻塞，但是子线程对象中的任务函数会继续执行，当任务执行完毕之后 join() 会清理当前子线程中的相关资源然后返回，同时，调用该函数的线程解除阻塞继续向下执行。</p>
<p>再次强调，我们一定要搞清楚这个函数阻塞的是哪一个线程，函数在哪个线程中被执行，**那么函数就阻塞哪个线程。**该函数的函数原型如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="kt">void</span> <span class="nf">join</span><span class="p">();</span>
</code></pre></div><p>有了这样一个线程阻塞函数之后，就可以解决在上面测试程序中的 bug 了，**如果要阻塞主线程的执行，只需要在主线程中通过子线程对象调用这个方法即可，当调用这个方法的子线程对象中的任务函数执行完毕之后，主线程的阻塞也就随之解除了。**修改之后的示例代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;string&gt;</span><span class="cp">
</span><span class="cp"></span><span class="cm">/*模拟下载任务-多线程的异步处理*/</span>
<span class="kt">void</span> <span class="nf">downLoad</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">file</span><span class="p">)</span>
<span class="p">{</span>
	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;DownLoading&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">file</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;(&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">i</span> <span class="o">*</span> <span class="mi">10</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;%)&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
		<span class="n">std</span><span class="o">::</span><span class="n">this_thread</span><span class="o">::</span><span class="n">sleep_for</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">milliseconds</span><span class="p">(</span><span class="mi">500</span><span class="p">));</span>
	<span class="p">}</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;DownLoading completed:&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">file</span><span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">void</span> <span class="nf">interact</span><span class="p">()</span>
<span class="p">{</span>
	<span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">name</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cin</span> <span class="o">&gt;&gt;</span> <span class="n">name</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;Hello&#34;</span> <span class="o">&lt;&lt;</span> <span class="s">&#34; &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">name</span><span class="o">&lt;&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t</span><span class="p">([</span><span class="o">&amp;</span><span class="p">](){</span>
        <span class="n">downLoad</span><span class="p">(</span><span class="s">&#34;hello.zip&#34;</span><span class="p">);</span>
    <span class="p">});</span>
    <span class="n">t</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="n">interact</span><span class="p">();</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><p>测试结果如下：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://raw.githubusercontent.com/jjking20010901/typora/master/img202208211549537.png"
        data-srcset="https://raw.githubusercontent.com/jjking20010901/typora/master/img202208211549537.png, https://raw.githubusercontent.com/jjking20010901/typora/master/img202208211549537.png 1.5x, https://raw.githubusercontent.com/jjking20010901/typora/master/img202208211549537.png 2x"
        data-sizes="auto"
        alt="https://raw.githubusercontent.com/jjking20010901/typora/master/img202208211549537.png"
        title="image-20220821154913477" /></p>
<p>当我们将下载函数放入另一个函数中并且在该函数中创建线程，然后将它放在主函数中，那么这时程序就会出现错误。</p>
<p>原因是当退出那个函数体时，会同时销毁线程，同时会自动调用线程中的析构函数，释放掉线程资源，但是下载函数可能还未执行完成，所以下载函数可能还未执行，线程就被摧毁了。</p>
<p>这时我们可以通过detach()分离线程来解决这个问题，下面讲一下detach()。</p>
<h2 id="3detach">3、detach()</h2>
<p><strong>detach() 函数的作用是进行线程分离，分离主线程和创建出的子线程。在线程分离之后，主线程退出也会一并销毁创建出的所有子线程，在主线程退出之前，它可以脱离主线程继续独立的运行，任务执行完毕之后，这个子线程会自动释放自己占用的系统资源。</strong>（其实就是孩子翅膀硬了，和家里断绝关系，自己外出闯荡了，如果家里被诛九族还是会受牵连）。</p>
<p>该函数的原型如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="kt">void</span> <span class="nf">detach</span><span class="p">();</span>
</code></pre></div><p>下面是上述问题的解决方法，只需要在那个函数体中加入detach()即可。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;string&gt;</span><span class="cp">
</span><span class="cp"></span><span class="cm">/*模拟下载任务-多线程的异步处理*/</span>
<span class="kt">void</span> <span class="nf">downLoad</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">file</span><span class="p">)</span>
<span class="p">{</span>
	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;DownLoading&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">file</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;(&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">i</span> <span class="o">*</span> <span class="mi">10</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;%)&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
		<span class="n">std</span><span class="o">::</span><span class="n">this_thread</span><span class="o">::</span><span class="n">sleep_for</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">milliseconds</span><span class="p">(</span><span class="mi">500</span><span class="p">));</span>
	<span class="p">}</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;DownLoading completed:&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">file</span><span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">void</span> <span class="nf">interact</span><span class="p">()</span>
<span class="p">{</span>
	<span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">name</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cin</span> <span class="o">&gt;&gt;</span> <span class="n">name</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;Hello&#34;</span> <span class="o">&lt;&lt;</span> <span class="s">&#34; &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">name</span><span class="o">&lt;&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">void</span> <span class="nf">myfunc</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t</span><span class="p">([</span><span class="o">&amp;</span><span class="p">](){</span>
        <span class="n">downLoad</span><span class="p">(</span><span class="s">&#34;hello.zip&#34;</span><span class="p">);</span>
    <span class="p">});</span>
    <span class="n">t</span><span class="p">.</span><span class="n">detach</span><span class="p">();</span>
<span class="p">}</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">myfunc</span><span class="p">();</span>
    <span class="n">interact</span><span class="p">();</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><p>调用成员函数detach()分离该线程，意味着线程的生命周期不再受当前std::thread对象所管理，而是在线程退出后自动销毁。</p>
<p>注意：</p>
<p><strong>线程分离函数 detach () 不会阻塞线程，子线程和主线程分离之后，在主线程中就不能再对这个子线程做任何控制了，比如：通过 join () 阻塞主线程等待子线程中的任务执行完毕，或者调用 get_id () 获取子线程的线程 ID。有利就有弊，鱼和熊掌不可兼得，建议使用 join ()。</strong></p>
<h2 id="4解决detach的问题">4、解决detach()的问题</h2>
<p>detach()的问题是进程退出的时候不会等待所有子线程执行完毕，并且在使用detach()分离线程时，当线程执行完成后会自动销毁。</p>
<p>那么我们可以通过将线程移动到全局线程池中，延长我们所创建线程的生命周期，这样就可以下载完成再退出进程。</p>
<p>下面是修改后的代码：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;string&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;vector&gt;</span><span class="cp">
</span><span class="cp"></span><span class="c1">//全局线程池
</span><span class="c1"></span><span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="kr">thread</span><span class="o">&gt;</span><span class="n">pool</span><span class="p">;</span>

<span class="cm">/*模拟下载任务-多线程的异步处理*/</span>
<span class="kt">void</span> <span class="nf">downLoad</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">file</span><span class="p">)</span>
<span class="p">{</span>
	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;DownLoading&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">file</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;(&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">i</span> <span class="o">*</span> <span class="mi">10</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;%)&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
		<span class="n">std</span><span class="o">::</span><span class="n">this_thread</span><span class="o">::</span><span class="n">sleep_for</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">milliseconds</span><span class="p">(</span><span class="mi">500</span><span class="p">));</span>
	<span class="p">}</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;DownLoading completed:&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">file</span><span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">void</span> <span class="nf">interact</span><span class="p">()</span>
<span class="p">{</span>
	<span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">name</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cin</span> <span class="o">&gt;&gt;</span> <span class="n">name</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;Hello&#34;</span> <span class="o">&lt;&lt;</span> <span class="s">&#34; &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">name</span><span class="o">&lt;&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">void</span> <span class="nf">myfunc</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t</span><span class="p">([</span><span class="o">&amp;</span><span class="p">](){</span>
        <span class="n">downLoad</span><span class="p">(</span><span class="s">&#34;hello.zip&#34;</span><span class="p">);</span>
    <span class="p">});</span>
    <span class="c1">//将线程t移动到线程池中，延长生命周期
</span><span class="c1"></span>    <span class="n">pool</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">t</span><span class="p">));</span>
<span class="p">}</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">myfunc</span><span class="p">();</span>
    <span class="n">interact</span><span class="p">();</span>
    <span class="c1">//等待线程池中所有的线程执行完成
</span><span class="c1"></span>    <span class="k">for</span><span class="p">(</span><span class="k">auto</span> <span class="o">&amp;</span><span class="nl">tt</span> <span class="p">:</span> <span class="n">pool</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">tt</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><p>上面的代码还是不太方便，需要修改main函数，我们可以创建一个ThreadPool类，在它的析构函数中手动添加join()，因为在main函数退出时会自动调用我们类中的析构函数，这样就不需要我们在main函数中手动修改了。</p>
<p>修改代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;string&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;vector&gt;</span><span class="cp">
</span><span class="cp"></span>
<span class="k">class</span> <span class="nc">ThreadPool</span>
<span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
   <span class="kt">void</span> <span class="n">push_back</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t</span><span class="p">)</span>
   <span class="p">{</span>
       <span class="n">m_pool</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">t</span><span class="p">));</span>
   <span class="p">}</span>
    <span class="c1">//main函数退出后自动调用
</span><span class="c1"></span>    <span class="o">~</span><span class="n">ThreadPool</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="c1">//等待线程池中的线程全部执行结束
</span><span class="c1"></span>        <span class="k">for</span><span class="p">(</span><span class="k">auto</span> <span class="o">&amp;</span><span class="nl">t</span> <span class="p">:</span> <span class="n">m_pool</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">t</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="k">private</span><span class="o">:</span>
    <span class="c1">//线程池
</span><span class="c1"></span>    <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="kr">thread</span><span class="o">&gt;</span><span class="n">m_pool</span><span class="p">;</span>
<span class="p">};</span>
<span class="c1">//声明全局线程池对象
</span><span class="c1"></span><span class="n">ThreadPool</span> <span class="n">pool</span><span class="p">;</span>

<span class="cm">/*模拟下载任务-多线程的异步处理*/</span>
<span class="kt">void</span> <span class="nf">downLoad</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">file</span><span class="p">)</span>
<span class="p">{</span>
	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;DownLoading&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">file</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;(&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">i</span> <span class="o">*</span> <span class="mi">10</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;%)&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
		<span class="n">std</span><span class="o">::</span><span class="n">this_thread</span><span class="o">::</span><span class="n">sleep_for</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">chrono</span><span class="o">::</span><span class="n">milliseconds</span><span class="p">(</span><span class="mi">500</span><span class="p">));</span>
	<span class="p">}</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;DownLoading completed:&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">file</span><span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">void</span> <span class="nf">interact</span><span class="p">()</span>
<span class="p">{</span>
	<span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">name</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cin</span> <span class="o">&gt;&gt;</span> <span class="n">name</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;Hello&#34;</span> <span class="o">&lt;&lt;</span> <span class="s">&#34; &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">name</span><span class="o">&lt;&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">void</span> <span class="nf">myfunc</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t</span><span class="p">([</span><span class="o">&amp;</span><span class="p">](){</span>
        <span class="n">downLoad</span><span class="p">(</span><span class="s">&#34;hello.zip&#34;</span><span class="p">);</span>
    <span class="p">});</span>
    <span class="c1">//将线程资源移交到线程池中，延长线程的生命周期
</span><span class="c1"></span>    <span class="n">pool</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">t</span><span class="p">));</span>
<span class="p">}</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">myfunc</span><span class="p">();</span>
    <span class="n">interact</span><span class="p">();</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div><div class="post-footer" id="post-footer">
    <div class="post-info"><div class="post-info-tag"><span><a href="/tags/thread%E7%9A%84%E4%BD%BF%E7%94%A8/">thread的使用</a>
                </span></div><div class="post-info-line"><div class="post-info-mod">
                <span>更新于 2022-08-21</span>
            </div><div class="post-info-mod"></div>
        </div><div class="post-info-share">
            <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://acking-you.gitee.io/posts/thread%C3%A7%C3%A4%C3%A7/" data-title="thread的使用" data-hashtags="thread的使用"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://acking-you.gitee.io/posts/thread%C3%A7%C3%A4%C3%A7/" data-hashtag="thread的使用"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://acking-you.gitee.io/posts/thread%C3%A7%C3%A4%C3%A7/" data-title="thread的使用" data-web><i class="fab fa-whatsapp fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://acking-you.gitee.io/posts/thread%C3%A7%C3%A4%C3%A7/" data-title="thread的使用"><i class="fab fa-line fa-fw"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://acking-you.gitee.io/posts/thread%C3%A7%C3%A4%C3%A7/" data-title="thread的使用" data-image="https://w.wallhaven.cc/full/9m/wallhaven-9m2pww.jpg"><i class="fab fa-weibo fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Myspace" data-sharer="myspace" data-url="https://acking-you.gitee.io/posts/thread%C3%A7%C3%A4%C3%A7/" data-title="thread的使用" data-description="thread的使用"><i data-svg-src="/lib/simple-icons/icons/myspace.min.svg"></i></a><a href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://acking-you.gitee.io/posts/thread%C3%A7%C3%A4%C3%A7/" data-title="thread的使用" data-description="thread的使用"><i class="fab fa-blogger fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Evernote" data-sharer="evernote" data-url="https://acking-you.gitee.io/posts/thread%C3%A7%C3%A4%C3%A7/" data-title="thread的使用"><i class="fab fa-evernote fa-fw"></i></a></span>
        </div></div><div class="post-nav"><a href="/posts/%C3%A6-%C3%A5%C3%A6%C3%A9%C3%A5%C2%BA%C3%A4thread/" class="prev" rel="prev" title="标准时间库chrono"><i class="fas fa-angle-left fa-fw"></i>Previous Post</a>
            <a href="/posts/%C3%A5%C3%A7%C2%BA%C3%A7%C3%A5%C3%A6api%C3%A8%C3%A8/" class="next" rel="next" title="多线程异步API解读">Next Post<i class="fas fa-angle-right fa-fw"></i></a></div></div>
</div></article></div>
            </main>
            <footer class="footer"><div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.86.0">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/khusika/FeelIt" target="_blank" rel="noopener noreffer" title="FeelIt 1.0.1"><i class="fas fa-hand-holding-heart fa-fw"></i> FeelIt</a>
        </div><div class="footer-line" itemscope itemtype="http://schema.org/CreativeWork"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2022</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/"></a></span></div>
</div>
</footer>
        </div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-chevron-up fa-fw"></i>
            </a></div><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><link rel="stylesheet" href="/lib/katex/katex.min.css"><link rel="stylesheet" href="/lib/katex/copy-tex.min.css"><script src="/lib/autocomplete/autocomplete.min.js"></script><script src="/lib/lunr/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="/lib/lazysizes/lazysizes.min.js"></script><script src="/lib/clipboard/clipboard.min.js"></script><script src="/lib/sharer/sharer.min.js"></script><script src="/lib/katex/katex.min.js"></script><script src="/lib/katex/auto-render.min.js"></script><script src="/lib/katex/copy-tex.min.js"></script><script src="/lib/katex/mhchem.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":200},"comment":{},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":100,"noResultsFound":"没有找到结果","snippetLength":50,"type":"lunr"}};</script><script src="/js/theme.min.js"></script></body></html>
